package com.lancoo.answer.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

public class CacheUtil {

    public static String getContentFromFile(String fileDir, String fileName) {

        //讀取文件内容並返回
        File file1 = new File(fileDir,fileName);
        String content = "";
        if (file1.exists()){
            content  = getFileContent(file1);
            Log.e("aaaaaaaaaaa","從文件獲取到的内容是"+content);
        }else {
            Log.e("aaaaaaaaaa","文件不存在");
        }
        return content;
    }

    public static void saveContentToFile(String fileDir, String fileName,String content) {
        //將内容保存到文本中
        writeTxtToFile(content,fileDir,fileName);
    }

    //读取指定目录下的所有TXT文件的文件内容
    public static String getFileContent(File file) {
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                try {
                    InputStream instream = new FileInputStream(file);
                    if (instream != null) {
                        InputStreamReader inputreader
                                = new InputStreamReader(instream, "UTF-8");
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line = "";
                        //分行读取
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }
                        instream.close();//关闭输入流
                    }
                } catch (java.io.FileNotFoundException e) {
                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content;
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        Log.e("aaa","写入文件中："+strcontent);
        try {
            File file = new File(filePath,fileName);
            if (file.exists()){
                file.delete();  //刪了重新寫
            }
            if (!file.exists()) {
                //       Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strcontent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }
}
